package com.qiqi.service.order.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.qiqi.dao.OrderMapper;
import com.qiqi.domain.Order;
import com.qiqi.domain.OrderExample;
import com.qiqi.service.order.OrderService;
@Service("orderService")
public class OrderServiceImpl implements OrderService{
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private JavaMailSenderImpl  mailSender;
	@Autowired
    private SimpleMailMessage templateMessage;
	public Map<String, Object> findOrderByPage(OrderExample query, int page,
			int pageSize) {
		page=page==0?1:page;
		pageSize=pageSize==0?20:pageSize;
		Map<String, Object> res=new HashMap<String, Object>();
		query.setLimitStart((page-1)*pageSize);
		query.setLimitEnd(pageSize);
		int count = orderMapper.countByExample(query);
		query.setOrderByClause("createTime desc");
		List<Order> list = orderMapper.selectByExample(query);
		res.put("list", list);
		res.put("total", count);
		return res;
	}
	public Map<String, Object> placeOrder(Order order, String host) {
		int state = orderMapper.insertSelective(order);
		Map<String, Object> res=new HashMap<String, Object>();
		res.put("success", state>0);
		if(state>0){
			//发送email
			try {
				String context="琪琪姐姐好，您有新的订单哦！<a href='"+host+"/order/"+order.getId()+"'>"+order.getNum()+"</a>";
				MimeMessage message = mailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(message, "UTF-8");
				helper.setTo(templateMessage.getTo()[0]);
				helper.setSubject(templateMessage.getSubject());
				helper.setFrom(templateMessage.getFrom());
				helper.setText(context,true);
				
				mailSender.send(message);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
	}

}
